package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author wfyn
 * @date 2023/10/5
 */
@Service

public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 新增菜品和口味
     * @param dishDTO 菜品DTO对象
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        // 创建一个Dish对象
        Dish dish = new Dish();

        // 将dishDTO的属性复制到dish对象中
        BeanUtils.copyProperties(dishDTO, dish);

        // 插入dish记录并获取生成的主键id
        dishMapper.insert(dish);
        Long id = dish.getId();

        // 获取口味列表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 遍历口味列表，设置对应的dishId
            flavors.forEach((item) -> item.setDishId(id));

            // 批量插入口味记录
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO pageQueryDTO) {

        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(pageQueryDTO);


        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {

        for (Long id : ids) {
            // 根据ID获取菜品信息
            Dish dish = dishMapper.getById(id);

            // 如果菜品状态为启用，抛出DeletionNotAllowedException异常
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 获取与菜品相关的套餐ID列表
        List<Long> setmealIds = setmealDishMapper.getSetmealByDishIds(ids);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            // 如果存在与菜品相关的套餐，抛出DeletionNotAllowedException异常
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

//        // 循环删除菜品和相关的口味
//        for (Long id : ids) {
//            // 删除菜品
//            dishMapper.deleteById(id);
//
//            // 删除与菜品关联的口味
//            dishFlavorMapper.deleteByDishIds(id);
//        }

        // 批量删除菜品和相关的口味
        dishMapper.deleteByIds(ids);
        // 批量删除与菜品关联的口味
        dishFlavorMapper.deleteByDishIds(ids);
    }
    /**
     * 起售,停售菜品
     * @param status
     * @param id
     * @return
     */
    @Override
    public void startOrStop(Integer status, Long id) {

        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();

        // 更新员工状态
        dishMapper.update(dish);

    }
    /**
     * 根据ID获取菜品信息
     * @param id
     * @return 返回dishVO对象
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        // 根据ID获取菜品信息
        Dish dish = dishMapper.getById(id);

        // 根据菜品ID获取菜品口味列表
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        // 创建DishVO对象
        DishVO dishVO = new DishVO();

        // 使用BeanUtils将dish的属性复制到dishVO中
        BeanUtils.copyProperties(dish, dishVO);

        // 设置菜品口味列表到dishVO
        dishVO.setFlavors(dishFlavors);

        // 返回dishVO对象
        return dishVO;
    }

    /**
     * 根据 DishDTO 对象更新 Dish 数据并处理口味信息
     *
     * @param dishDTO 包含更新信息的 DishDTO 对象
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        // 创建 Dish 对象并将属性拷贝
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 更新 Dish 数据
        dishMapper.update(dish);

        // 删除该 Dish 的口味信息
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        // 获取口味列表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            Long dishId = dishDTO.getId();

            // 设置对应的 dishId
            flavors.forEach(item -> item.setDishId(dishId));

            // 批量插入口味记录
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> getDishByCategoryId(Long categoryId) {


        return dishMapper.getByIdCategoryIde(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            Integer saleCount = orderMapper.getSaleByDishId(d.getId());
            saleCount=  saleCount == null ? 0: saleCount;
            dishVO.setCopies(saleCount);
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}



